var roleObj = {
  "1": "业主公司",
  "2": "建筑公司",
  "3": "项目经理",
  "4": "班组承包人",
  "5": "分包班组单位",
  "6": "建筑工人",
  "7": "设备供应商",
  "8": "设施供应商",
  "9": "材料供应商"
};
var accTypeObj = {
  "1": "主",
  "2": "子",
  "3": "其他"
};

$(function () {
  init();

  // 右上隐藏按钮
  $('.hide-selector').click(function () {
    $('.condition').css('display') == 'none' ?
        $('.condition').show() : $('.condition').hide();
  })
});

function init() {
  $(".mask-layer").hide();
}

// 加载页面
$('.view-container').load('tpl/loginadmin.html', loginadminCallBack);

// 登录管理起始页返回函数
function loginadminCallBack() {
  aPreDef();
  // 新增按钮点击事件
  $('.dropdown-menu').on('click', 'li', function () {
        // 设置自定义属性值
        $('.view-container').attr('data-type', $(this).children('a').html());
        skipPage(this, createCallBack);
      }
  );

  isValidSelector();

  var selectHtml = "<option value=''>全部</option>";
  createRoleOptions(selectHtml, $('#userRole'));
  $('#loginData').bootstrapTable({
    url: 'data/user.json',//todo 表格预留接口
    onClickRow: function (row) {
      var IDNum = row.userCode;
      $.getJSON('data/user-' + IDNum + '.json', function (data) {
        data.accType = accTypeObj[data.accType];
        data.isValid = data.isValid == 0 ? "未启用" : "已启用";
        data.ctime = getRecordDate(data.ctime);
        $(".modle-show").load("tpl/popupframe/details.html", function () {
          compile(data)
        });
        $(".view-datails").show();
      });
    }
  })
}

// 创建账号返回函数
function createCallBack() {
  aPreDef();
  var type = $(this).attr('data-type');
  var usingState = parseInt($('#usingState').val());

  // 设置面包屑
  $('.breadcrumb').children('.active').removeClass('active')
      .parent().append('<li class="active">新建' + type + '</li>');

  // 标题
  $('.create-header').append('<span>新建' + type + '</span>');
  $('.create-time').val(getRecordDate());
  $('.select-lessee-model').hide();

  // 启用/停用开关绘制及isValid参数的修改
  drawUsingState(usingState);
  $('#isValidContainer span').html(usingState ? '启用' : '停用');
  $('#isValidContainer').on('click', function () {
    usingState = usingState ? 0 : 1;
    $('#usingState').val(usingState);
    drawUsingState(usingState);
    $(this.querySelector('span')).html(usingState ? '启用' : '停用');
  });

  loadLesseeModel(); //加载租户选择页面

  // 返回按钮
  $('.create-come-back').click(function () {
    resetBreadCrumb();
    skipPage(this, loginadminCallBack);
  });

  // 点击弹出窗口
  $('#lessee').on('click', function () {
    selectLessee(); //弹出窗口
  });

    createMsgSub(type);

}

// 租户选择页面加载
function loadLesseeModel() {

  // 租户选择模态框
  $('.select-lessee-model').load('tpl/select-lessee.html', function () {

    var selectHtml = "";
    createRoleOptions(selectHtml, $('#lessee-type'));

    $('.new-close').click(closeModel);

    setBSTable(); //设置bootstrapTable

    //todo 获取租户角色接口
    //$.getJSON('url',function(data){
    //   根据data进行options创建并插入select内
    // })

    // 查询按钮点击事件
    $('#lessee-submit').on('click', function (e) {
      e.preventDefault();
      var type = $('#lessee-type').val();
      var selector = $('#lessee-selector').val();
      var input = {"typeName": type, "selectorName": selector};
      console.log(input);

      //todo 传递条件并返回数据or接口
      //$.get(getLesseeUrl,input,function(data){
      //   console.log(data);
      // })
    })
  });
}

// 注册时间格式转换
function getRecordDate(date) {
  var time = date ? (new Date(parseInt(date))) : (new Date);
  var Y = time.getFullYear();
  var M = time.getMonth();
  var D = time.getDate();
  return Y + '年' + M + '月' + D + '日';
}

// 打开租户选择模态框
function selectLessee() {
  //$(".mask-layer").show();
  $('.select-lessee-model').show();
}

// 页面跳转
function skipPage(elem, callback) {
  var url = $(elem).children('a').attr('href');
  $('.view-container').load(url, callback);
}

// 阻止a标签页面默认事件
function aPreDef() {
  $('a').on('click', function (e) {
    e.preventDefault();
  });
}

// 设置bootstrapTable
function setBSTable() {
  $('#lessee-table').bootstrapTable({
    //url: "http://192.168.59.104:8080/shixiaobao/basedata/user/UserList/1/8", //todo 表格数据接口
    url: 'data/user.json',
    onClickRow: lesseeTableRowClick
  });
}
// bootstrapTable行点击事件
function lesseeTableRowClick(row) {
  $('#lessee').val(row.userCode + ' ' + row.userName);
  closeModel();
}

function responseHandler(response) {
    console.log(response);
    sessionStorage.setItem('data',JSON.stringify(response));
  var data = {
    rows: response.data
  };
  return data;
}

// 重置面包屑
function resetBreadCrumb() {
  $('.breadcrumb').children('.active')
      .prev().addClass('active').next().remove();
}
// 关闭模态框
function closeModel() {
  $(".mask-layer").hide();
  $('.select-lessee-model').hide();
}

// 动态生成租户角色列表
function createRoleOptions(html, fn) {
  for (var key in roleObj) {
    html += `<option value="${key}">${roleObj[key]}</option>`;
  }
  fn.html(html);
}

function createMsgSub(type) {
    // 完成按钮点击事件
    $('#createSub').on('click', function (e) {
        e.preventDefault();
        //var state = 'peer';
        var msg = {};
        msg.accountType = type == '主账号' ? 1 : (type == "子账号" ? 2 : 3);
        $('#createForm [data-name]').each(function (i, elem) {
            //if (!$(elem).val()) {
            //  state = 'forbid';
            //  return;
            //}
            if (elem.nodeName=='IMG') {
                msg[$(elem).attr('data-name')]=$(elem).attr('src');
            }else if(elem.nodeName=='INPUT'){
                if($(elem).attr('data-name')=='lessee'){
                    var lesseeMsg=$(elem).val().split('');
                    msg.userCode=lesseeMsg[0];
                    msg.userName=lesseeMsg[1];
                }else{
                    msg[$(elem).attr('data-name')]=$(elem).val();
                }
            }
            delete msg.accNum;
        });
        console.log(msg);
        $.ajax({
            type:'post',
            url:'http://192.168.59.104:8080/shixiaobao/basedata/user',
            data:msg,
            dataType:'json',
            contentType:'application/x-www-form-urlencoded;charset=UTF-8',
            success:function(data){
                console.log(String(data));
            },
            error:function(err){
                console.log(String(err))
            }
        })
    })
}


function drawUsingState(state) {
  var canvas = $('#usingStateCanvas')[0];
  var ctx = canvas.getContext('2d');
  ctx.lineWidth = 2;
  ctx.clearRect(0, 0, 42, 16);
  ctx.beginPath();
  ctx.moveTo(11, 1);
  ctx.lineTo(31, 1);
  ctx.arc(31, 8, 7, Math.PI * 3 / 2, Math.PI / 2, false);
  ctx.lineTo(11, 15);
  ctx.arc(11, 8, 7, Math.PI / 2, Math.PI * 3 / 2, false);
  if (state) {
    ctx.strokeStyle = '#3280fc';
    ctx.fillStyle = '#3280fc';
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(12, 8, 5, 0, Math.PI * 2, false);
    ctx.fill();
  } else {
    ctx.strokeStyle = '#999';
    ctx.fillStyle = '#999';
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(30, 8, 5, 0, Math.PI * 2, false);
    ctx.fill();
  }
}